<!--
 * @Author: zcc
 * @Date: 2021-08-31 14:08:33
 * @LastEditors: Please set LastEditors
 * @Description: watch监听
 * @FilePath: /workProject/vue3/vue3Learn/vue3-learn/src/views/CompositionsApi/watch.vue
-->
<template>
  <div class="contain">
    <h1>清除监听</h1>
    <div>在 setup() 函数内创建的 watch 监视，会在当前组件被销毁的时候自动停止。如果想要明确地停止某个监视，可以调用 watch() 函数的返回值即可，语法如下：</div>
    <p>
      // 创建监视，并得到 停止函数
      const stop = watch(() => {
      /* ... */
      })
      // 调用停止函数，清除对应的监视
      stop()
    </p>
  </div>
</template>

<script>
import { onMounted, reactive, ref, toRefs, watch, watchEffect } from "vue";
export default {
  name: "watch",
  setup() {
    // 1.监听ref数据
    let a = ref(0);
    setTimeout(() => {
      a.value++;
    }, 2000);
    watch(a, (newA, oldA) => {
      console.log(newA, oldA, "监听ref");
    });

    // 2.监视 reactive 类型的数据源
    const state = reactive({
      count: 1,
      name: "cc",
      color: "red",
      age: 18
    });
    watch(
      () => state.count,
      (a, b) => {
        console.log(a, b, "监听reactive");
      }
    );
    setTimeout(() => {
      state.count++;
    }, 2000);

    // 3.监听监视多个数据源
    watch(
      [() => state.age, () => state.name, () => state.color],
      ([a, b, c], [d, e, f]) => {
        console.log(a, b, c); // a b c 是三个新的值，d e f是旧的值，
      },
      {
        lazy: true // 在 watch 被创建的时候，不执行回调函数中的代码
      }
    );
    setTimeout(() => {
      state.age++;
      state.name = "zcc";
      state.color = "green";
    }, 2000);

    // 创建监视，并得到 停止函数
    const stop = watch(() => {
      /* ... */
    });

    // 调用停止函数，清除对应的监视
    stop();

    return {
      a,
      ...toRefs(state)
    };
  }
};
</script>

<style lang="scss" scoped>
</style>
